$m(function (args) {
    var $this = $(this.element).closest("body");
    this.jobDialog = null;
    this.flowsParam = {};
    flowInfo = {};
    var that = this;
    var rowDatas = {};
    var seleccount = 0;
    var failedCount = 0;
    var successCount = 0;
    var successSche = 0;
    var failSche = 0;
    var shezhiDiv = $(".tempo-scheduing-shezhi-div");
    var allDatas = []//所有数据集
    var scheduling = "";
    var selectStatus = "false";
    // 定义一个判断用户是否点击筛选-查询的标识
    var isSearch = false;
    // 定义一个存储点击筛选-查询时，筛选里所有框的信息
    var searchData = {};

    flows = [];
    var ceilsName = [
        "trigger.name",
        "workspaceName",
        "applicationName",
        "creatorName",
        "createTime",
        "trigger.prevtime",
        "trigger.nexttime",
        "cost",
        "trigger.state",//调度状态
        "trigger.status",
        "logs"
    ];
    var setColumnName = [
        "creatorName",
        "createTime",
        "trigger.prevtime",
        "trigger.nexttime",
        "cost",
        "trigger.state",//调度状态
        "trigger.status",
        "logs"
    ];
    //添加表格列方法
    var addCeils = function () {
        selectStatus = "true";
        var newceilsArray = getCeils();
        var grid = $('#mine-opt-job-grid');
        for (i = 0; i < newceilsArray.length; i++) {
            if (newceilsArray[i]) {
                grid.jqGrid("showCol", ceilsName[i]);
            } else {
                grid.jqGrid("hideCol", ceilsName[i]);
            }
        }
    }
    /*
	保存调度列设置信息
	 */
    var saveColumnInfo = function () {

        var columnInfo = "";//列显示信息字符串
        var columnSelectInfo = getColumnSet();
        for (var i = 0; i < setColumnName.length; i++) {
            columnInfo += setColumnName[i] + ":" + columnSelectInfo[i] + ",";
        }
        $.ajax({
            url: contextPath + '/api/ai/job/save-jobcolumninfo',
            type: 'post',
            async: false,
            data: {
                columnInfo: columnInfo
            },
            success: function (obj) {

            }
        });
    }

    /**
     * 获取调度列保存信息
     */
    var getColumnInfo = function () {

        $.ajax({
            url: contextPath + '/api/ai/job/get-jobcolumninfo',
            type: 'post',
            data: {
                test: 'test'
            },
            success: function (obj) {
                var colinfo = obj[0].colInfoArr || [];
                var arr = [];
                var newInfo = [];//获取的用户设置的列显示信息数组
                for (var i = 0; i < colinfo.length; i++) {
                    arr.push(colinfo[i].split(":"));
                    newInfo.push(arr[i][1]);
                }
                var grid = $('#mine-opt-job-grid');
                for (i = 0; i < newInfo.length; i++) {
                    if (newInfo[i] == "true") {
                        grid.jqGrid("showCol", setColumnName[i]);
                    } else {
                        grid.jqGrid("hideCol", setColumnName[i]);
                    }
                }
                //return newInfo;
            },
            error: function (message) {

            }
        });
    }
    //点击确定时，刷新用户设置的显示列
    $("#tempo-addCeilsBt").off('click').on('click', function () {
        shezhiDiv.removeClass("tempo-scheduing-shezhi-div-show");
        shezhiDiv.css("display", "none");
        shezhiDiv.slideUp;
        saveColumnInfo();
        getColumnInfo();
        //重新渲染表格
        that.grid.datagrid("reloadGrid");

    })
    var paramLabel = TempoUtils.locale("mine.publish-mine-job-param-label");
    $this.find("#jobContainer").layout({
        north: {
            resizable: false,
            size: 100,
            spacing_open: 0
        },
        center: {
            onresize: TempoUtils.throttle(function () {
            }, 200, true)
        }
    });

    //为暂停按钮绑定筛选事件
    $("#tempo-task-pause").off('click').on('click', function () {
        scheduling = "PAUSED";
        $(".tempo-head-szBt").addClass("tempo-task-other");
        $(this).removeClass("tempo-task-other");
        $(this).css("background-color", "#dfe9fd ");
        $(this).css("color", "#5185e4 ;");
        $(".tempo-task-other").css("background-color", "#eee ");
        $(".tempo-task-other").css("color", "dimgray ");
        that.grid.datagrid("reloadGrid", {jobstatus: scheduling});
        bindJobGridEvent();
        $(this).addClass("tempo-task-other");
        $(".after_select").hide();
    });
    //为“生效”按钮绑定筛选事件
    $(".tempo-task-running").off('click').on('click', function () {
        scheduling = "WAITE";
        $(".tempo-head-szBt").addClass("tempo-task-other");
        $(this).removeClass("tempo-task-other");
        $(this).css("background-color", "#dfe9fd ");
        $(this).css("color", "#5185e4 ;");
        $(".tempo-task-other").css("background-color", "#eee ");
        $(".tempo-task-other").css("color", "dimgray");
        that.grid.datagrid("reloadGrid", {jobstatus: scheduling});
        bindJobGridEvent();
        $(".after_select").hide();

    });
    //为等待按钮添加筛选事件
    $(".tempo-task-waite").off('click').on('click', function () {

        scheduling = "AWAIT";
        $(".tempo-head-szBt").addClass("tempo-task-other");
        $(this).removeClass("tempo-task-other");
        $(this).css("background-color", "#dfe9fd ");
        $(this).css("color", "#5185e4 ;");
        $(".tempo-task-other").css("background-color", "#eee ");
        $(".tempo-task-other").css("color", "dimgray ");
        that.grid.datagrid("reloadGrid", {jobstatus: scheduling});
        bindJobGridEvent();
        $(this).addClass("tempo-task-other");
        $(".after_select").hide();
    });
    //为”失效“按钮添加筛选条件
    $(".tempo-task-complete").off('click').on('click', function () {
        scheduling = "COMPLETE";
        $(".tempo-head-szBt").addClass("tempo-task-other");
        $(this).removeClass("tempo-task-other");
        $(this).css("background-color", "#dfe9fd ");
        $(this).css("color", "#5185e4 ;");
        $(".tempo-task-other").css("background-color", "#eee ");
        $(".tempo-task-other").css("color", "dimgray ");
        that.grid.datagrid("reloadGrid", {jobstatus: scheduling});
        bindJobGridEvent();
        $(".after_select").hide();
    });
    //为“全部”按钮绑定筛选事件
    $(".tempo-task-all").off('click').on('click', function () {
        scheduling = "";
        $(".tempo-head-szBt").addClass("tempo-task-other");
        $(this).removeClass("tempo-task-other");
        $(this).css("background-color", "#dfe9fd !important");
        $(this).css("color", "#5185e4 ;");
        $(this).css("border-width", "0px !important");
        $(".tempo-task-other").css("background-color", "#eee ");
        $(".tempo-task-other").css("color", "dimgray ");
        that.grid.datagrid("reloadGrid", {jobstatus: scheduling});
        $("#jqgh_mine-opt-job-grid_trigger.state").css("text-align", "left");
        $(".after_select").hide();

    });
    /**
     * 从数据库中获取列状态，并设置齿轮图标打开后的复选框值
     */
    var getJobColumnInfo = function () {
        $.ajax({
            url: contextPath + '/api/ai/job/get-jobcolumninfo',
            type: 'post',
            async: false,
            data: {
                test: 'test'
            },
            success: function (obj) {
                var colinfo = obj[0].colInfoArr || [];
                var arr = [];
                var info = [];
                var selectFlag = [];
                for (var i = 0; i < colinfo.length; i++) {
                    arr.push(colinfo[i].split(":"));
                    info.push(arr[i][1]);
                    if (info[i] == "true") {
                        selectFlag.push(true);
                    } else {
                        selectFlag.push(false);
                    }
                }
                $("#tempo-creator").prop("checked", selectFlag[0]);
                $("#tempo-createtime").prop("checked", selectFlag[1]);
                $("#tempo-preStartTime").prop("checked", selectFlag[2]);
                $("#tempo-nextStartTime").prop("checked", selectFlag[3]);
                $("#tempo-preSpendTime").prop("checked", selectFlag[4]);
                $("#tempo-isrunning").prop("checked", selectFlag[5]);
                $("#tempo-status").prop("checked", selectFlag[6]);
                $("#tempo-log").prop("checked", selectFlag[7]);
            },
            error: function (message) {

            }
        });
    }
    //为表头设置图标绑定点击事件
    $("#tempo-shezhi").off('click').on('click', function (e) {

        shezhiDiv.mouseleave(function () {
            shezhiDiv.hide();
            getJobColumnInfo();
        });
        shezhiDiv.toggle(function () {
            if (shezhiDiv.hasClass("tempo-scheduing-shezhi-div-show")) {
                // if(changeColumnSet.length <=  0){
                // 	changeColumnSet = TempoUtils.clone(getColumnSet());
                // }
                getJobColumnInfo();
                shezhiDiv.css("display", "");
                shezhiDiv.slideDown;
                shezhiDiv.css("left", e.pageX - 200);
                shezhiDiv.css("top", e.pageY + 20);
                shezhiDiv.removeClass("tempo-scheduing-shezhi-div-show");

            } else {
                shezhiDiv.addClass("tempo-scheduing-shezhi-div-show")
                //shezhiDiv.removeClass("tempo-scheduing-shezhi-div-hidden");
            }
        })
    });
    var sizerDivShow = function (one) {
        $("#shaixuanDiv").slideToggle();
        $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-downarrows-thin");
        $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-uparrows-thin");
        $('.tempo-tableset').slideToggle(1);
        $(document).off('click').on("click", function (e) {
            var target = $(e.target);
            if (target.closest(one).length == 0) {
                $("#shaixuanDiv").hide();
                $('.tempo-tableset').show();
                $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-downarrows-thin");
                $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-uparrows-thin");

                $(document).off('click');
            }

        });
    }
    //筛选框弹出事件绑定
    $("#shaix").click(function () {
        sizerDivShow("#shaixuanDiv,#shaix,.tempo-sizer-icon,.ui-datepicker-title,.ui-datepicker-current,.mark,.ui-datepicker-close,.ui-datepicker-calendar,#ui-datepicker-div,.ui-datepicker-prev,.ui-datepicker-next");
    });
    //筛选图标点击事件
    $(".tempo-sizer-icon").click(function () {
        sizerDivShow("#shaixuanDiv,#shaix,.tempo-sizer-icon,.ui-datepicker-title,.ui-datepicker-current,.mark,.ui-datepicker-close,.ui-datepicker-calendar,#ui-datepicker-div,.ui-datepicker-prev,.ui-datepicker-next");
    });
    //筛选框位置计算
    var sxtop = $("#shaix").offset().top;
    var sxleft = $("#shaix").offset().left;
    console.log("横坐标" + sxtop);
    $("#shaixuanDiv").css("top", sxtop + 30);
    $("#shaixuanDiv").css("left", sxleft - 360);
    //为筛选框添加图标提示
    $(".sizer").blur(function () {
        // 获取筛选div里的搜索input框
        var inputs = $('#shaixuanDiv').find('input');
        // 定义是否有数据标识 true表示有数据
        var hasValue = false;
        for (var i = 0; i < inputs.length; i++) {
            if (inputs.eq(i).val().trim() != "") {
                hasValue = true;
                break;
            }
        }
        // 如果搜索框中有值，则显示图标
        if (hasValue) {
            $("#ifshaixuan").removeAttr('style');
            $(".sizer-reset").css("color", "#5185e4")
        } else {
            $("#ifshaixuan").hide();
        }
    });
    //表头设置按钮位置计算
    $('.tempo-tableset').css("top", sxtop + 40);
    $('.tempo-tableset').css("left", sxleft - 20);
    //重置按钮点击事件
    $(".sizer-reset").click(function () {
        // 将搜索状态改为false，并清空筛选数据
        isSearch = false;
        searchData = {};
        $("#ifshaixuan").hide();
        $("[name='starttime']").datepicker("destroy");
        $("[name='endtime']").datepicker("destroy");
        $("[name='laststarttime']").datepicker("destroy");
        $("[name='lastendtime']").datepicker("destroy");
        $("[name='createStartTime']").datepicker("destroy");
        $("[name='createEndTime']").datepicker("destroy");
        $(".tempo-sizer-inputright input").val("");
        that.grid.datagrid("clearGridData");
        initOrrefresh(false);

        var starttime = form.find('[name="starttime"]').datepicker('getDate');
        var endtime = form.find('[name="endtime"]').datepicker('getDate');
        var laststarttime = form.find('[name="laststarttime"]').datepicker('getDate');
        var lastendtime = form.find('[name="lastendtime"]').datepicker('getDate');
        var jobstatus = form.find('[name="jobstatus"]').val();
        var jobname = form.find('[name="jobname"]').val();
        var jobcreator = form.find('[name="jobcreator"]').val();
        var workspaceName = form.find('[name="workspaceName"]').val();
        var applicationName = form.find('[name="applicationName"]').val();
        var lastExcuteStatus = form.find('[name="lastExcuteStatus"]').val();
        var createStartTime = form.find('[name="createStartTime"]').datepicker('getDate');
        var createEndTime = form.find('[name="createEndTime"]').datepicker('getDate');


        var data = {
            starttime: starttime ? DateUtils.formatDate(starttime, 'yyyy-MM-dd') : null,
            endtime: endtime ? DateUtils.formatDate(endtime, 'yyyy-MM-dd') : null,
            laststarttime: laststarttime ? DateUtils.formatDate(laststarttime, 'yyyy-MM-dd') : null,
            lastendtime: lastendtime ? DateUtils.formatDate(lastendtime, 'yyyy-MM-dd') : null,
            name: jobname,
            creator: jobcreator,
            jobstatus: jobstatus,
            workspaceName: workspaceName,
            applicationName: applicationName,
            lastExcuteStatus: lastExcuteStatus,
            createStartTime: createStartTime ? DateUtils.formatDate(createStartTime, 'yyyy-MM-dd') : null,
            createEndTime: createEndTime ? DateUtils.formatDate(createEndTime, 'yyyy-MM-dd') : null,
            querydata: "true"
        };
        $this.find(".ui-icon-seek-first").trigger("click");
        setTimeout(function () {
            that.grid.jqGrid('setGridParam',
                {
                    postData: data
                }).trigger("reloadGrid");
            delete data["querydata"];
            $this.find(".tempo-ui-icon-refresh").trigger("click");
        }, 500);
    });
    //为手动执行绑定事件
    $(".tempo-manual").off('click').on('click', function () {
        var rowId = $(this).attr("rowId");
        var rowData = rowDatas[rowId];
        if (rowData.isRunning == "true") {
            $("<div/>").alert({msg: rowData.trigger.name + "任务正在执行，请稍后发起手动执行", height: 180});
            return;
        }
        $(".after_select").hide();
        manualJob(rowData);
    })
    //为删除按钮绑定删除事件
    $(".tempo-delete").off('click').on('click', function () {
        var rowId = $(this).attr("rowId");
        var rowData = rowDatas[rowId];
        $(".after_select").hide();
        deleteJob(rowData);
    });


    var DataObserveCenter = (function () {
        var manualArray = {};
        var stopArray = {};
        return {
            manualJob: function (id) {
                manualArray[id] = true;
            },
            isObserve: function (id) {
                return !!manualArray[id];
            },
            remove: function (id) {
                if (manualArray[id])
                    delete manualArray[id];
                if (stopArray[id])
                    delete stopArray[id];
            },
            isStop: function (id) {
                return !!stopArray[id];
            },
            stopJob: function (id) {
                stopArray[id] = true;
            }
        }
    })();
    //不同筛选状态下重新渲染列表数据
    var resetTableData = function (resetdata) {
        $this.find('#mine-opt-job-grid').datagrid("clearGridData");
        $this.find('#mine-opt-job-grid')[0].addJSONData(resetdata);
    }
    //获取勾选框结果
    var getCeils = function () {
        var checkedCeils = [];
        checkedCeils.push(true);//应用名称
        checkedCeils.push(true);//所属空间
        checkedCeils.push(true);//所属应用
        checkedCeils.push($("#tempo-creator").is(":checked"));
        checkedCeils.push($("#tempo-createtime").is(":checked"));
        checkedCeils.push($("#tempo-preStartTime").is(":checked"));
        checkedCeils.push($("#tempo-nextStartTime").is(":checked"));
        checkedCeils.push($("#tempo-preSpendTime").is(":checked"));
        checkedCeils.push($("#tempo-isrunning").is(":checked"));
        checkedCeils.push($("#tempo-status").is(":checked"));
        checkedCeils.push($("#tempo-log").is(":checked"));
        return checkedCeils;
    };
    var getColumnSet = function () {
        var columnSetArr = [];
        columnSetArr.push($("#tempo-creator").is(":checked"));
        columnSetArr.push($("#tempo-createtime").is(":checked"));
        columnSetArr.push($("#tempo-preStartTime").is(":checked"));
        columnSetArr.push($("#tempo-nextStartTime").is(":checked"));
        columnSetArr.push($("#tempo-preSpendTime").is(":checked"));
        columnSetArr.push($("#tempo-isrunning").is(":checked"));
        columnSetArr.push($("#tempo-status").is(":checked"));
        columnSetArr.push($("#tempo-log").is(":checked"));
        return columnSetArr;
    }

    /**
     * 运行任务
     */
    var runJob = function (job) {
        $.ajax({
            url: contextPath + '/mine/publish/runJob',
            type: 'post',
            data: {
                id: job.id,
                triggerId: job.jobId
            },
            success: function (obj) {
                if (obj) {
                    console.log(obj);
                }
            }
        });
    }

    /**
     * 停止任务
     */
    var stopJob = function (job, callback) {
        //删除调度任务
        DataObserveCenter.stopJob(job.id);
        var process = $("<div/>").tempoprogressbar();
        $.ajax({
            url: contextPath + '/api/ai/app/schedule/job/stop',
            type: 'post',
            data: {
                id: job.id,
                triggerId: job.jobId,
                logNum: job.successCount + job.failedCount
            },
            dataType: 'json',
            success: function (obj) {
                process.tempoprogressbar("destroy");
                if (callback == "true") {
                    that.grid.datagrid("reloadGrid");
                }
                if (obj.success) {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.publish-job-killed"), height: 180});
                } else {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.publish-job-notexists"), height: 180});
                }

            }
        });
    }
    /**
     * 点击...图标显示更多选择的div
     */
    var showMore = function (job) {

    }
    /**
     * 暂停任务
     */
    var pauseJob = function (job) {
        var process = $("<div/>").tempoprogressbar();
        var url = contextPath + '/api/ai/app/schedule/job/pause';
        if (job.trigger.status == 'PAUSED') {
            url = contextPath + '/api/ai/app/schedule/job/restart'
        } else if (job.trigger.status == 'COMPLETE') {
            process.tempoprogressbar("destroy");
            $("<div/>").alert({
                msg: TempoUtils.locale("mine.renwuyijingwancheng"),
                height: 180
            });
            return false;
        }
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data: {
                id: job.id, triggerId: job.jobId
            },
            success: function (obj) {
                process.tempoprogressbar("destroy");
                if (job.status != 'PAUSED') {
                    if (obj && obj.success == false) {
                        $("<div/>").alert({
                            msg: TempoUtils.locale("mine.renwuyijingyunxing"),
                            height: 180
                        });
                    }
                }
                $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
            }
        });
    }

    /**
     * 手动执行
     */
    var manualJob = function (job) {
        var process = $("<div/>").tempoprogressbar();
        $.ajax({
            url: contextPath + "/api/ai/app/schedule/job/manual",
            type: 'post',
            data: {
                id: job.id,
                triggerId: job.jobId
            },
            dataType: 'json',
            success: function (obj) {
                process.tempoprogressbar("destroy");
                if (obj.success) {
                    DataObserveCenter.manualJob(job.id);
                    $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                } else {
                    $("<div/>").alert({
                        msg: TempoUtils.locale("mine.renwuzhixingzhong"),
                        height: 180
                    });
                }
            }
        });
    }

    /**
     * 删除调度任务
     */
    var deleteJob = function (job) {
        var jobId = job.jobId;
        $("<div/>").confirm({
            width: 500,
            height: 197,
            msg: TempoUtils.locale("mine.publish-mine-job-grid-col-delete-confirm"),
            ok: function () {
                var process = $("<div/>").tempoprogressbar();
                $.ajax({
                    url: contextPath + '/api/ai/app/schedule/job/delete',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        triggerId: jobId,
                        id: job.id
                    },
                    success: function (obj) {
                        process.tempoprogressbar("destroy");
                        $this.find(".tempo-ui-icon-refresh").trigger("click");
                        $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                    }
                });
            }
        });
    }

    /**
     * 编辑调度任务
     */
    var editJob = function (job) {
        newJob.apply(that, [job, true]);
    }

    var getCurrentFlowParams = function (dialog) {
        var paramsTable = dialog.find('#task-flowParamsContainer table');
        var currentFlowParams = []
        var paramsLine = paramsTable.find('tbody tr');
        paramsLine.each(function (i) {
            var paramName = $(this).find('input.flow_paramname').val();
            var paramType = $(this).find('input.flow_paramtype').val();
            var paramId = $(this).find('input.flow_paramid').val();
            var paramValue = $(this).find('select.flow_paramvalue').selectmenu('getValue');
            if (paramName) {
                var param = {};
                param.paramName = paramName;
                param.paramValue = paramValue;
                param.paramId = paramId;
                param.paramType = paramType;
                if (!$.isEmptyObject(param)) {
                    currentFlowParams.push(param);
                }
            }
        });
        return currentFlowParams;
    }

    var setFlowParams = function (dialog, job) {
        var flowParams = job ? JSON.parse(job.trigger.param) : null;
        var flowParam = null;
        if (flowParams != null) {
            flowParam = flowParams.flowsParam;
        }
        dialog.find('#flowParamsContainer').hide();
        var paramLabel = TempoUtils.locale("mine.publish-mine-job-param-label");
        dialog.find("#publish-mine-job-param-label").text(job.publishFlowNames + '-' + paramLabel);
        var grid = dialog.find('#setFlowParamTable').find('tbody').empty();
        if (flowParam != null) {
            var params = flowParam[job.publishFlowIds];
            if (!params || params.length == 0) {
                $.ajax({
                    url: contextPath + "/api/ai/app/schedule/flowparams/get/" + job.publishFlowIds,
                    type: 'post',
                    success: function (result) {
                        if (result && result.data && result.data.length > 0) {
                            initParamGrid(dialog, result.data);
                        }
                    }
                });
            } else {
                initParamGrid(dialog, params);
            }
        }
    }
    var getFlowParams = function (type, paramValueInput, value, nodeType) {
        var pss = [];
        if (type == 'datasource') {
            var process = $("<div/>").tempoprogressbar();
            $.ajax({
                url: contextPath + '/api/ai/node/io/list-datasources',
                type: 'post',
                success: function (rs) {
                    process.tempoprogressbar("destroy");
                    var data = rs.data;
                    var itemHtml = [];
                    if (data) {
                        for (var i = 0; i < data.length; i++) {
                            var dataItem = data[i];
                            // 屏蔽模型数据源、presto数据源、impala数据源
                            if (nodeType == 'readrdbms') {
                                if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
                                    continue;
                                }
                            }
                            if (nodeType == 'writerdbms') {
                                if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
                                    continue;
                                }
                            }

                            if (nodeType == 'readhive') {
                                if (dataItem.type != 'hive') {
                                    continue;
                                }
                            }
                            if(nodeType == 'writehive'){
                                if('hive' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")){
                                    continue;
                                }
                            }
                            if (nodeType == "readinfluxdb") {
                                if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
                                    continue;
                                }
                            }
                            if( nodeType == "readiotdb"){
                                if (dataItem.type != 'iotdb') {
                                    continue;
                                }
                            }
                            if( nodeType == "writeiotdb"){
                                //不是iotdb  或者不能写入
                                if ('iotdb' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")) {
                                    continue;
                                }
                            }
                            itemHtml.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
                        }
                    }
                    var html = itemHtml.join('');
                    paramValueInput.html(html);
                    paramValueInput.selectmenu({
                        editable: false,
                        width: 150,
                        labelForTitle: true
                    }).selectmenu('setValue', value).selectmenu('refresh');
                }
            });
        } else {
            var items = TempoMineUtils.getConstFlowParams();
            if (items) {
                for (name in items) {
                    pss.push('<option value="' + name + '">' + items[name] + '</option>')
                }
            }
            var html = pss.join('');
            paramValueInput.html(html);
            paramValueInput.selectmenu({
                editable: true,
                width: 150,
                labelForTitle: true
            }).selectmenu('setValue', value);
        }

    }

    var initParamGrid = function (dialog, ps) {
        var grid = dialog.find('#setFlowParamTable');
        dialog.find('#task-flowParamsContainer').show();
        dialog.find('#tempo-mine-flow-param').show();
        if (ps && ps.length > 0) {
            var count = 0;
            var flag = false;
            for (var i = 0; i < ps.length; i++) {
                // 屏蔽系统参数
                if ('system.appId' == ps[i].paramName) {
                    flag = true;
                    continue;
                }
                var tr = $('<tr>').appendTo(grid);
                var p = ps[i];
                var paramName = p.paramName;
                var paramValue = p.paramValue;
                var paramType = p.paramType;
                var nodeType = p.nodeType;
                if (!paramName) {
                    continue;
                }
                if ("configResources" == paramType) {
                    count++;
                    continue;
                }
                var paramNameTd = $('<td>').appendTo(tr);
                var paramNameInput = $('<input name="paramName">')
                    .addClass('flow_paramname')
                    .appendTo(paramNameTd)
                    .val(paramName);
                var paramValueTd = $('<td>').appendTo(tr);
                var paramValueInput = $('<select name="paramValue">').addClass('flow_paramvalue').appendTo(paramValueTd);
                paramNameInput.validatebox({width: 100, readonly: true});

                paramNameInput.attr('title', paramName);
                getFlowParams(paramType, paramValueInput, paramValue, nodeType);
            }
            if (count == ps.length) {
                dialog.find('#task-flowParamsContainer').hide();
            }
            if (ps.length == 1 && flag) {
                dialog.find('#task-flowParamsContainer').hide();
            }
        } else {
            dialog.find('#task-flowParamsContainer').hide();
        }
    }

    /**
     * 新增调度
     */
    var newJob = function (job, isEdit) {

        that.flowsParam = {};
        that.jobDialog = $($this.find('.tempo-mine-flow-task-dialog')[0]).clone().appendTo('body');
        var dialogTitle = TempoUtils.locale('mine.publish-mine-job-dialog-title');
        if (isEdit) {
            dialogTitle = TempoUtils.locale('mine.publish-mine-job-edit-dialog-title');
        }
        that.jobDialog.dialog({
            width: 750,
            height: 550,
            autoOpen: false,
            title: dialogTitle,
            modal: true,
            resizable: false,
            close: function () {
                that.jobDialog.dialog("destroy");
            },
            buttons: [{
                text: TempoUtils.locale('mine.publish-dialog-sure'),
                click: function () {
                    saveJobConfig.apply(that, [job, isEdit]);
                }
            }, {
                text: TempoUtils.locale('mine.publish-dialog-cancel'),
                click: function () {
                    that.jobDialog.dialog("close");
                }
            }]
        });
        that.jobDialog.dialog('open');
        initJobLayout.apply(that, isEdit ? [job] : null);
    }

    /**
     * 初始化表单数据
     */
    var initFormData = function (job) {

        var dialog = that.jobDialog;
        job = job || {};
        TempoUtils.parserUi(dialog, job);

        dialog.find('input[name="retry"]').checkbox({
            change: function (e, ui) {
                console.log(e, ui);
                if (ui.checked) {
                    dialog.find('input[name="retryNum"]').numberbox({disabled: false, required: true});
                } else {
                    dialog.find('input[name="retryNum"]').numberbox({disabled: true, required: false});
                }
            }
        });

        dialog.find('.datefield').datepicker({
            dateFormat: 'yy-mm-dd',
            onClose: function () {
                if ($(this).val()) {
                    $(this).validatebox('response', $(this).val());
                }
            },
            onSelect: function () {

            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                $.datepicker._hideDatepicker(this);
            }
        });
        dialog.find('.timefield').timepicker({
            onClose: function () {
                if ($(this).val()) {
                    $(this).validatebox('response', $(this).val());
                }
            },
            onSelect: function () {

            },
            timeInput: true
        });

        var internalInput = dialog.find('input[name=interval]');
        dialog.find('select[name="triggertype"]').selectmenu({
            selectFirst: false,
            change: function (e, ui) {
                console.log(e, ui);
                changeTriggerType(ui.item.value);
            }
        });

        var changeTriggerType = function (value) {
            if (value == "-2") {
                //分钟
                switchShowItem(dialog, false, true, false, true, 1);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-minute"));
                internalInput.numberbox({max: 59, min: 1}).val(30);
            } else if (value == "-1") {
                //小时
                switchShowItem(dialog, false, true, false, true, 1);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-hour"));
                internalInput.numberbox({max: 23, min: 1}).val(3);
            } else if (value == "0") {
                //天
                switchShowItem(dialog, false, false, true, true, 3);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-day"));
                internalInput.numberbox({max: 31, min: 1}).val(1);
            } else if (value == "1") {
                //周
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-week"));
                switchShowItem(dialog, true, false, true, false);
                buildWeeks(dialog);
                internalInput.numberbox({max: 6, min: 1}).val(1);
            } else if (value == "2") {
                //月
                switchShowItem(dialog, true, false, true, true, 2);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-month"));
                buildDays(dialog);
                internalInput.numberbox({max: 11, min: 1}).val(1);
            }
        }

        //调度名称
        if (!$.isEmptyObject(job)) {
            dialog.find('input[name="starttime"]').val(job.trigger.starttime);
            dialog.find('input[name="endtime"]').val(job.trigger.endtime);
            dialog.find('input[name="stime"]').val(job.trigger.stime);
            dialog.find('input[name="etime"]').val(job.trigger.etime);
            dialog.find('select[name="priority"]').val(job.trigger.priority).selectmenu('refresh');
            dialog.find('input[name="id"]').val(job.id);
            dialog.find('input[name="name"]').val(job.trigger.name);
            dialog.find('select[name="triggertype"]').val(job.trigger.triggertype).selectmenu('refresh');
            changeTriggerType(job.trigger.triggertype);
            internalInput.val(job.trigger.interval);
            if (job.trigger.rundate) {
                var days = job.trigger.rundate.split(",");
                if (job.trigger.triggertype == '1') {
                    dialog.find('input[name=dayofweek]').each(function () {
                        var $this = $(this);
                        if (days.indexOf($this.val()) > -1) {
                            $this.checkbox('check', $this.val());
                        }
                    });
                } else if (job.trigger.triggertype == '2') {
                    dialog.find('input[name=dayofmonth]').each(function () {
                        var $this = $(this);
                        if (days.indexOf($this.val()) > -1) {
                            $this.checkbox('check', $this.val());
                        }
                    });
                }
            }
            if (job.trigger.runType) {
                dialog.find('input[name=runType]').radio('check', job.trigger.runType);
            }
            if ((job.trigger.triggertype == '-2' || job.trigger.triggertype == '-1')
                && job.trigger.runType != 'inner-day' && job.trigger.runType != 'outer-day') {
                dialog.find('input[name=runType]').radio('check', 'inner-day');
            }
            if (job.trigger.retry) {
                dialog.find('input[name=retry]').click();
                dialog.find('input[name=retryNum]').numberbox({
                    disabled: false,
                    required: true,
                    value: job.trigger.retryNum
                });
            }
        } else {
            dialog.find('select[name="triggertype"]').val(0).selectmenu('refresh');
            changeTriggerType(0);
            dialog.find('input[name=starttime]').val(DateUtils.formatDate(new Date()));
        }
    }

    /**
     * 调度时间切换方法
     */
    var switchShowItem = function (dialog, timesRow, timeRange, dayTime, interval, dayMonthYear) {
        var _onoff = $.fn.onoff;
        $.fn.onoff = function (value) {
            var element = $(this);
            if (value) {
                element.show();
            } else {
                element.hide();
            }
            element.find('input').each(function (index, ele) {
                var role = $(ele).attr('ui-role');
                if (role == 'validatebox' || role == 'numberbox') {
                    !value ? $(ele)[role]('disable') : $(ele)[role]('enable');
                }
            });
        }
        dialog.find('.times-row').onoff(timesRow);
        dialog.find('.times-board').empty();
        if (timeRange) {
            dialog.find('.day-of-time-range-row input[name=stime]')
                .validatebox({required: true}).validatebox('validate');
        } else {
            dialog.find('.day-of-time-range-row input[name=stime]')
                .validatebox({required: false}).validatebox('validate');
        }
        dialog.find('.day-of-time-range-row').onoff(timeRange);
        dialog.find('.day-of-time-row').onoff(dayTime);
        dialog.find('.time-interval-row').onoff(interval);
        if (interval && dayMonthYear != undefined) {
            dialog.find('.time-of-day').onoff(dayMonthYear == 1);
            dialog.find('input.time-of-day').hide().radio('check', dayMonthYear == 1 ? 'outer-day' : '');
            dialog.find('.day-of-month').onoff(dayMonthYear == 2);
            dialog.find('input.day-of-month').hide().radio('check', dayMonthYear == 2 ? 'outer-month' : '');
            dialog.find('.month-of-year').onoff(dayMonthYear == 3);
            dialog.find('input.month-of-year').hide().radio('check', dayMonthYear == 3 ? 'outer-year' : '');
        }
        $.fn.onoff = _onoff;
    }

    /**
     * 构建周页面
     */
    var buildWeeks = function (dialog) {
        var board = dialog.find('.times-board');
        var weeks = [2, 3, 4, 5, 6, 7, 1];
        var weekName = [TempoUtils.locale("mine.xinqiyi"),
            TempoUtils.locale("mine.xinqier"),
            TempoUtils.locale("mine.xinqisan"),
            TempoUtils.locale("mine.xinqisi"),
            TempoUtils.locale("mine.xinqiwu"),
            TempoUtils.locale("mine.xinqiliu"),
            TempoUtils.locale("mine.xinqitian")
        ];
        weeks.forEach(function (e, i) {
            var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
            $("<input ui-role='checkbox' name='dayofweek' type='checkbox'/>").val(e).appendTo(span);
            $("<label/>").text(weekName[i]).appendTo(span);
        });
        TempoUtils.parserUi(board, {});
    };

    /**
     * 构建天页面
     */
    var buildDays = function (dialog) {
        var board = dialog.find('.times-board');
        for (var i = 1; i <= 31; i++) {
            var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
            $("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
                .val(i)
                .addClass('day-of-month-' + i)
                .appendTo(span);
            $("<label/>").text(i + TempoUtils.locale("mine.hao")).appendTo(span);
        }
        var lastSpan = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
        $("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
            .val("L")
            .addClass('day-of-month-L')
            .appendTo(lastSpan);
        $("<label/>").text(TempoUtils.locale("mine.zuihouyitian")).appendTo(lastSpan);
        TempoUtils.parserUi(board, {});
    }

    /**
     * 保存调度信息
     */
    var saveJobConfig = function (oldjob, isEdit) {

        var dialog = this.jobDialog;
        if (!validateForm(dialog, isEdit, oldjob.trigger.name)) {
            return;
        }
        var job = {
            trigger: {},
            publishFlowIds: []
        };
        job.id = oldjob.id;
        job.jobId = oldjob.jobId;
        job.creator = oldjob.creator;
        job.createTime = oldjob.createTime;
        job.trigger.id = oldjob.jobId;

        var triggerParam = {};
        var trigger = job.trigger;
        var publishFlowIds = [];
        var publishFlowNames = [];
        //调度信息
        var jobconfig = dialog.find('#tempo-mine-flow-config-task').serializeArray();

        // 添加对复选框值的处理，转变为一个属性值
        $.each(jobconfig, function (index, item) {
            if (!item.name.startsWith('flow_')) {
                if (trigger[item.name]) {
                    if (Array.isArray(trigger[item.name])) {
                        trigger[item.name].push(item.value);
                    } else {
                        trigger[item.name] = [trigger[item.name], item.value];
                    }
                } else {
                    trigger[item.name] = item.value;
                }
            }
        });
        // 解决IE10下面选中保存不了问题
        var isChecked = dialog.find('input[name=retry]').is(':checked');
        if (!trigger.retry && isChecked) {
            trigger.retry = 'on';
        }
        //由于之前的界面改动，此处的优先级信息需要手动获取，wtf
        // 上面的注释不是我加的，我也不敢删除，所以就加了这句注释
        if (!trigger.priority) {
            var priority = dialog.find('select[name="priority"]').val();
            trigger.priority = priority;
        }
        if ((dialog.find('input[name=dayofweek]').length && !trigger['dayofweek'])
            || (dialog.find('input[name=dayofmonth]').length && !trigger['dayofmonth'])) {
            $("<div/>").alert({msg: TempoUtils.locale("mine.qingxuanzeyunxingshijian"), height: 180});
            return false;
        }
        // 处理数组类型值，转换为逗号分割的字符串
        Array.isArray(trigger['dayofweek']) && (trigger['rundate'] = trigger['dayofweek'].join(','));
        Array.isArray(trigger['dayofmonth']) && (trigger['rundate'] = trigger['dayofmonth'].join(','));
        trigger['dayofweek'] && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofweek']);
        trigger['dayofmonth'] && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofmonth']);
        delete trigger['dayofweek'];
        delete trigger['dayofmonth'];
        console.log(JSON.stringify(trigger))
        trigger.interval = Number(trigger.interval);
        if (trigger.retryNum) trigger.retryNum = Number(trigger.retryNum);

        var oldJobParamJson = JSON.parse(oldjob.trigger.param);
        triggerParam.flowsInJob = oldJobParamJson.flowsInJob;
        if (!triggerParam.flowsInJob || triggerParam.flowsInJob == undefined) {
            var relatedFlow = [];
            var rflowObj = {};
            rflowObj["flow_current"] = oldjob.publishFlowIds;
            relatedFlow.push(rflowObj);
            triggerParam.flowsInJob = relatedFlow;
        }
        job.publishFlowIds = oldjob.publishFlowIds;
        job.publishFlowNames = oldjob.publishFlowNames;
        //流程配置参数
        triggerParam.flowsParam = {};
        triggerParam.flowsParam[oldjob.publishFlowIds] = getCurrentFlowParams(dialog);
        job.trigger.param = JSON.stringify(triggerParam);

        var process = $("<div/>").tempoprogressbar();
        var url = contextPath + '/api/ai/app/schedule/job/update';
        $.ajax({
            url: url,
            type: 'post',
            data: JSON.stringify(job),
            contentType: 'application/json',
            success: function (obj) {
                process.tempoprogressbar("destroy");
                dialog.dialog("close");
                if (obj && obj.data && obj.data.status) {
                    $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                } else {
                    $("<div/>").alert({msg: obj.data.error, height: 180, width: 400});
                }
            },
            error: function (data) {
                process.tempoprogressbar("destroy");
                dialog.dialog("close");
            }
        });
    }

    /**
     * 新增调度对话框
     */
    var initJobLayout = function (job) {

        initFormData.apply(that, [job]);
        setFlowParams(that.jobDialog, job);
    }

    /**
     * 调度列表事件
     */
    var bindJobGridEvent = function () {

        // $(".ui-common-table").css("width","100%");
        var grid = $this.find('#mine-opt-job-grid');


        grid.find(".edit-job-btn").unbind("click").bind("click", function (e) {
            e.stopPropagation();
            var rowid = $(e.target).attr('rowid');
            var row = grid.jqGrid("getRowData", rowid);
            editJob.apply(that, [row]);
        });
        grid.find(".run-job-btn").unbind("click").bind("click", function (e) {
            e.stopPropagation();
            var rowid = $(e.target).attr('rowid');
            var row = grid.jqGrid("getRowData", rowid);
            runJob(row);
        });
        grid.find(".stop-job-btn").unbind("click").bind("click", function (e) {
            e.stopPropagation();
            var rowid = $(e.target).attr('rowid');
            var row = grid.jqGrid("getRowData", rowid);
            stopJob(row, "true");
            // stopJob(row, function() {
            // 	grid.jqGrid().trigger("reloadGrid");
            // });
        });
        grid.find(".del-job-btn").unbind("click").bind("click", function (e) {
            e.stopPropagation();
            var rowid = $(e.target).attr('rowid');
            var row = grid.jqGrid("getRowData", rowid);
            deleteJob(row);
        });

        grid.find(".log-job-btn").unbind("click").bind("click", function (e) {
            e.stopPropagation();
            var rowid = $(e.target).attr('rowid');
            var log = $(e.target).attr('logid');
            var runResult = $(e.target).attr('runResult');
            var row = grid.jqGrid("getRowData", rowid);
            downloadLog(row.id, log, runResult);
        });
        //成功/失败状态按钮点击事件
        grid.find(".successStatusCount").off('click').on('click', function (e) {

            var rowid = $(e.target).attr('rowId');
            var jobid = $(e.target).attr('jobId');
            var row = rowDatas[rowid];
            td = $(e.target).attr('rowid');
            //var row = grid.datagrid('getRowData', rowid);
            viewDetail(row);
        });
        grid.find(".viewlog").each(function () {

            var rowid = $(this).attr('rowid');
            var row = null;
            var rows = grid.data('rows');
            if (rows && rows.length > 0) {
                for (var m = 0; m < rows.length; m++) {
                    if (rowid == rows[m].id) {
                        row = rows[m];
                    }
                }
            }
            var logs = row.logs;
            var content;
            if (logs && logs.length > 0) {
                var logele = $('<ul>').css({
                    'list-style-type': 'none'
                });
                for (var i = 0; i < logs.length; i++) {
                    var log = logs[i];
                    var date = new Date(parseFloat(log.runTime));
                    var runResult = log.runResult;
                    var icon = "ui-icon ui-icon-document";
                    if (runResult != null) {
                        if (runResult == 0) {
                            icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-errorprompt";
                        } else if (runResult == 1) {
                            icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-check-thin";
                        }
                    }
                    var logName = DateUtils.formatDateTime(date, 'yyyy-MM-dd HH:mm:ss')
                    var liele = $('<li class="logitem">').attr('jobid', rowid).attr('logid', log.id).attr('runResult', log.runResult).attr('name', logName);
                    var liicon = $("<span>").addClass(icon).appendTo(liele);
                    var lilabel = $("<label>").text(logName).appendTo(liele);
                    logele.append(liele);
                }
                content = $('<div>').append(logele).html();
            }
            var height = 'auto';
            if (logs && logs.length > 0 && logs.length > 5) {
                height = 100;
            } else if (logs && logs.length > 0 && logs.length <= 5) {
                height = logs.length * 20;
            }
            $(this).webuiPopover({
                trigger: 'hover',
                title: '',
                cache: false,
                placement: 'right',
                width: 195,
                height: height,
                arrow: true,
                content: content
            });
            $(this).on('shown.webui.popover', function () {

                $('.logitem').each(function (index, domEle) {
                    $(domEle).off('click').on('click', function () {
                        var jobid = $(this).attr('jobid');
                        var logid = $(this).attr('logid');
                        var runResult = $(this).attr('runResult');
                        var name = $(this).attr('name');
                        downloadLog(jobid, logid, name, runResult);
                    })
                });
            });
        });
        //点击任务名称，跳转任务详情界面
        grid.find('.tempo-datagrid-trigger-name').off('click').on("click", function (e, job) {

            var rowid = $(e.target).attr('rowid');
            var flowid = $(e.target).attr('flowId');
            var row = rowDatas[flowid];
            viewDetail(row);
        });
    }

    /**
     * 下载任务日志
     */
    var downloadLog = function (id, log, name, runResult) {
        TempoUtils.downLoadFile({
            url: contextPath + "/api/ai/mine/publish/downloadJobLog",
            data: {
                id: id,
                name: name,
                log: log,
                runResult: runResult
            }
        });
    }

    var viewDetail = function (job) {
        openViewDetailDialog(job);
    }

    //当成功失败次数太多时显示不下，因此根据数量扩展外层div大小
    var extendDiv = function (num, object) {

        var oldWidth = object.width();
        if (num >= 100000 && num < 1000000) {
            object.css("width", oldWidth + 20);
        } else if (num >= 1000000) {
            object.css("width", oldWidth + 40);
        }
    }
    /**
     * 初始化列表
     */

    var initJobGrid = function () {
        that.grid = $this.find('#mine-opt-job-grid').datagrid({
            datatype: "json",
            url: contextPath + '/api/ai/mine/publish/listJobAi?time=' + new Date().getTime(),
            postData: {},
            fit: true,
            autowidth: true,
            mtype: 'POST',
            rownumbers: true,
            shrinkToFit: false,//滚动条
            autoscroll: true,
            viewrecords: true,
            pagination: true,
            showRefreshBth: true,//是否显示刷新按钮
            striped: true,
            multiselect: true,
            //勾选后的触发事件
            onSelectRow: function () {
                var selecspan = $(".selectedSpan");
                $(".tempo-datagrid-trigger-name").css("color", "black");
                var grid = $this.find('#mine-opt-job-grid');
                var selected = grid.datagrid("getSelectRowIds");
                seleccount = selected.length;
                ;
                if (seleccount != 0) {
                    selecspan.text("已选择" + " " + seleccount + " " + "条");
                }
                $(".after_select").css("display", "");
                if (seleccount == 0) {
                    $(".after_select").css("display", "none");
                }
                //全选按钮是否选中
                if (that.grid.find("input").length == seleccount) {
                    that.grid.parent().parent().parent().find("input[id$='_mine-opt-job-grid']").prop("checked", true);
                }
            },
            colNames: [
                'id',
                'jobId',
                'logNum',
                TempoUtils.locale("mine.publish-mine-job-grid-col-name"),//'调度名称'
                '所属空间',
                '所属应用',
                'triggertype',
                'priority',
                'endtime',
                'param',
                'creator',
                TempoUtils.locale("mine.publish-mine-job-grid-col-creator"),//'创建者'
                '创建时间',
                TempoUtils.locale("mine.publish-mine-job-grid-col-lasttime"),//'上次执行时间'
                TempoUtils.locale("mine.publish-mine-job-grid-col-nexttime"),//'下一次执行时间'
                "下次执行时间",
                TempoUtils.locale("mine.publish-mine-job-grid-col-lastcosttime"),//'上一次执行耗时'
                '调度状态',//'状态'
                TempoUtils.locale("mine.zhixingqingkuang"),
                '日志',
                TempoUtils.locale("mine.publish-mine-job-grid-col-opt"),//'操作'
            ],
            colModel: [{
                name: 'id',
                index: 'id',
                hidden: true
            }, {
                name: 'jobId',
                index: 'jobId',
                hidden: true
            }, {
                name: 'logNum',
                sortable: false,
                hidden: true,
                formatter: function (obj, grid, rows, state) {
                    successSche = rows.successCount || 0;
                    failSche = rows.failedCount || 0;
                    var logNum = successSche + failSche;
                    return logNum
                }
            }, {
                name: 'trigger.name',
                index: 'trigger.name',
                sortable: false,
                hidden: false,
                formatter: function (obj, rows, grid) {
                    rowDatas[grid.CATEGORYID] = grid;
                    var html = "<a href='javascript:void(0);' class='tempo-datagrid-trigger-name' style='text-decoration: none' rowid='" + rows.rowId + "'flowId='" + grid.id + "'>" + TempoMineUtils.encodeHTML(obj) + "</a>";
                    return html;
                }
            },
                {
                    name: 'workspaceName',
                    index: 'workspaceName',
                    hidden: false,
                    sortable: false,
                    formatter: function (obj, rows, grid) {
                        if (obj == null) {
                            return "";
                        }
                        return obj.replace(/</g, "&lt;").replace(/>/g, '&gt;');
                    }
                }, {
                    name: 'applicationName',
                    index: 'applicationName',
                    hidden: false,
                    sortable: false,
                    formatter: function (obj, rows, grid) {
                        return obj.replace(/</g, "&lt;").replace(/>/g, '&gt;');
                    }
                }, {
                    name: 'trigger.triggertype',
                    index: 'trigger.triggertype',
                    hidden: true
                }, {
                    name: 'trigger.priority',
                    index: 'trigger.priority',
                    hidden: true
                }, {
                    name: 'trigger.endtime',
                    index: 'trigger.endtime',
                    hidden: true
                }, {
                    name: 'trigger.param',
                    index: 'trigger.param',
                    hidden: true
                }, {
                    name: 'creator',
                    index: 'creator',
                    hidden: true
                }, {
                    name: 'creatorName',
                    index: 'creatorName',
                    sortable: false

                }, {
                    name: 'createTime',
                    index: 'createTime',
                    hidden: false,
                    sortable: false,

                }, {
                    name: 'trigger.prevtime',
                    index: 'trigger.prevtime',
                    align: 'center',
                    resizable: false,
                    hidden: false,
                    formatter: function (obj, grid, rows, state) {
                        if (obj && rows.cost >= 0) {
                            return obj;
                        } else {
                            return "";
                        }
                    }
                }, {
                    name: 'trigger.nexttime',
                    index: 'trigger.nexttime',
                    align: 'center',
                    align: 'center',
                    resizable: false,
                    hidden: true,
                    formatter: function (obj, grid, rows, state) {
                        if (rows.trigger.status == "PAUSED") {
                            return '--';
                        } else {
                            return obj || '--';
                        }
                    }
                }, {
                    name: 'isRunning',
                    index: 'isRunning',
                    hidden: true
                }, {
                    name: 'cost',
                    index: 'cost',
                    align: 'center',
                    resizable: false,
                    sortable: false,
                    formatter: function (obj, grid, rows, state) {
                        if (rows.cost >= 0 && rows.isRunning != "true") {
                            return rows.cost + TempoUtils.locale("mine.publish-mine-job-exe-second");
                        }
                        return "";
                    }
                }, {
                    name: 'trigger.state',
                    index: 'trigger.state',
                    sortable: false,
                    align: 'center',
                    formatter: function (obj, grid, rows, state) {

                        if (rows.trigger.status == "PAUSED") {
                            return '<span class=" trigger-status test-pasue">暂停</span>';
                        } else if (rows.trigger.status == "COMPLETE") {
                            return '<span class=" trigger-status test-undo">失效</span>';
                        } else if (rows.trigger.status == "AWAIT") {
                            return '<span class=" trigger-status test-undo">等待</span>';
                        } else {
                            return '<span class=" trigger-status test-passed">生效</span>';
                        }
                    }
                }, {
                    name: 'trigger.status',
                    index: 'trigger.status',
                    sortable: false,
                    title: false,
                    formatter: function (obj, grid, rows, state) {
                        successSche = rows.successCount || 0;
                        failSche = rows.failedCount || 0;
                        var titleSuc = successSche;
                        var titleFail = failSche;
                        if (parseInt(successSche) > 9999) {
                            successSche = successSche.toString().substr(0, 3) + ".." || 0;
                        }
                        if (parseInt(failSche) > 9999) {
                            failSche = failSche.toString().substr(0, 3) + ".." || 0;
                        }
                        var htm = "<button class='successStatusCount state_succ_bt' style='width: 57px;height: 20px;color:#5185e4' border='1px solid #5185e4 !important' title='成功" + titleSuc + "' jobId='" + rows.jobId + "' rowId='" + rows.id + "'>" + "成功" + (successSche > 100 ? 10 + "." : successSche) + "</button>" + "<button class='faildStatusCount state_fail_bt' title='失败" + titleFail + "' style='width: 57px;height: 20px;color:#fc7f7f;margin-left: 5px'>" + "失败" + (failSche > 100 ? 10 + "." : failSche) + "</button>";
                        return htm;
                    }
                }, {
                    name: 'logs',//日志
                    index: '',
                    sortable: false,
                    align: 'center',
                    hidden: true,
                    formatter: function (obj, grid, rows, state) {
                        //
                        var logs = rows.logs;
                        if (logs && logs.length > 0) {
                            return "<a href='javascript:;void(0)' rowid='" + rows.id + "' class='viewlog run-logs' style='text-decoration: none;cursor: pointer'>" + TempoUtils.locale("mine.publish-mine-job-log-view") + "</a>";
                        }
                        return '';
                    }
                }, {
                    sortable: false,
                    align: 'center',
                    buttons: [
                        {
                            id: "kill",
                            icon: "ui-icon tempo-ui-icon tempo-ui-icon-kill",
                            title: TempoUtils.locale("mine.publish-btn-stop"),
                            click: function (e, dt) {
                                var rowid = dt.rowId;
                                var row = dt.rowData;
                                stopJob(row, function () {
                                    that.grid.jqGrid().trigger("reloadGrid");
                                });
                            }
                        }, {
                            id: "pause",
                            title: TempoUtils.locale("mine.publish-btn-pause"),
                            beforeAdd: function (rowId, rowData, btn) {
                                if (rowData.trigger.status == "COMPLETE") {
                                    btn.icon = "ui-icon tempo-ui-icon tempo-ui-icon-resume";
                                    btn.title = TempoUtils.locale("mine.publish-btn-start");
                                } else if (rowData.trigger.status == "PAUSED") {
                                    btn.icon = "ui-icon tempo-ui-icon tempo-ui-icon-resume";
                                    btn.title = TempoUtils.locale("mine.publish-btn-start");
                                } else {
                                    btn.icon = "ui-icon tempo-ui-icon tempo-ui-icon-pause";
                                    btn.title = TempoUtils.locale("mine.publish-btn-pause");
                                }
                            },
                            click: function (e, dt) {
                                var rowid = dt.rowId;
                                var row = dt.rowData;
                                pauseJob(row);
                            }
                        },
                        {
                            id: "more",
                            icon: "ui-icon tempo-ui-icon tempo-ui-icon-more",
                            title: "更多",
                            click: function (e, obj, rows) {
                                var that1 = this;
                                var rowid = $(obj).attr('rowId');
                                var row = obj.rowData;
                                var rowData = $(obj).attr('rowData');
                                var sel_more = $(".tempo-select-more");
                                $(".tempo-manual").attr("rowId", rowid);
                                $(".tempo-manual").attr("rowData", rowData);

                                $(".tempo-delete").attr("rowId", rowid);
                                $(".tempo-delete").attr("rowData", rowData);
                                var mousex = e.pageX;
                                var mousey = e.pageY;
                                sel_more.css("left", mousex + 18);
                                sel_more.css("top", mousey);


                                $(document).off('click').on("click", function (e) {
                                    var target = $(e.target);
                                    if (target.closest(that.grid.find('.tempo-ui-icon-more')).length == 0) {
                                        $(sel_more).hide();

                                    } else {
                                        $(sel_more).show();
                                    }
                                });
                                sel_more.mouseleave(function () {
                                    $(sel_more).hide();
                                });

                                return row;

                            }
                        }
                    ]
                }
            ],

            loadComplete: function (datas) {
                //为解决问题：39697 微服务-挖掘-外网UAT-成果管理：主版本 1点击异步服务的筛选按钮，输入内容之后，筛选符号向上，点击同步服务时，筛选按钮也变成了向上
                $this.find(".tempo-sizer-icon").removeClass("ui-icon tempo-ui-icon tempo-ui-icon-uparrows-thin");
                $this.find(".tempo-sizer-icon").addClass("ui-icon tempo-ui-icon tempo-ui-icon-downarrows-thin");
                var rows = datas.rows;
                if (rows.length > 0) {
                    $(".ui-paging-info").show();
                } else {
                    $(".ui-paging-info").hide();
                }
                $(".ui-state-default").css("padding-left", "0px");
                $(".ui-state-default").css("padding-right", "0px");
                $(".after_select").hide();
                var waiteSucCount = 0;
                var awaitSucCount = 0;
                var pauseSucCount = 0;
                var completeSucCount = 0;
                var waiteFailCount = 0;
                var awaitFailCount = 0;
                var pauseFailCount = 0;
                var completeFailCount = 0;
                var rows = datas.rows;
                var allSuccCounts = 0;
                var allFailCounts = 0;
                var searchDataTmp = {};
                if (isSearch) {
                    searchDataTmp = searchData;
                } else {
                    searchDataTmp = {
                        starttime: null,
                        endtime: null,
                        laststarttime: null,
                        lastendtime: null,
                        name: "",
                        creator: "",
                        jobstatus: "",
                        workspaceName: "",
                        applicationName: "",
                        lastExcuteStatus: "",
                        createStartTime: null,
                        createEndTime: null,
                        querydata: "true"
                    };
                }
                $.ajax({
                    url: contextPath + "/api/ai/mine/publish/listJobAi",
                    type: 'post',
                    data: searchDataTmp,
                    success: function (result) {

                        var resultdata = result.rows;
                        //将所有数据放入所有结果集中
                        allDatas = resultdata;
                        for (var i = 0; i < resultdata.length; i++) {
                            var jobInfo = resultdata[i];
                            var trigger = jobInfo.trigger;
                            rowDatas[resultdata[i].id] = resultdata[i]
                            if ("PAUSED" == trigger.status || "PAUSED_BLOCKED" == trigger.status) {
                                if (resultdata[i].successCount != undefined) {
                                    pauseSucCount += resultdata[i].successCount;
                                    pauseFailCount += resultdata[i].failedCount;
                                } else {
                                    pauseSucCount += 0;
                                    pauseFailCount == 0;
                                }
                            } else if ("COMPLETE" == trigger.status) {
                                if (resultdata[i].successCount != undefined) {
                                    completeSucCount += resultdata[i].successCount;
                                    completeFailCount += resultdata[i].failedCount;
                                } else {
                                    completeSucCount += 0;
                                    completeFailCount == 0;
                                }
                            } else if ("AWAIT" == trigger.status) {
                                if (resultdata[i].successCount != undefined) {
                                    awaitSucCount += resultdata[i].successCount;
                                    awaitFailCount += resultdata[i].failedCount;
                                } else {
                                    awaitSucCount += 0;
                                    awaitFailCount == 0;
                                }
                            } else if ("WAITE" == trigger.status) {
                                if (resultdata[i].successCount != undefined) {
                                    waiteSucCount += resultdata[i].successCount;
                                    waiteFailCount += resultdata[i].failedCount;
                                } else {
                                    waiteSucCount += 0;
                                    waiteFailCount == 0;
                                }
                            }
                        }
                        allSuccCounts = completeSucCount + awaitSucCount + waiteSucCount + pauseSucCount;
                        allFailCounts = pauseFailCount + waiteFailCount + awaitFailCount + completeFailCount;

                        $("#jqgh_mine-opt-job-grid_").css("padding-left", "10px");
                        $("#jqgh_mine-opt-job-grid_trigger.state").css("text-align", "left");
                        if (scheduling == "PAUSED") {
                            $(".tempo-task-succeed").val("成功" + pauseSucCount);
                            $(".tempo-task-failed").val("失败" + pauseFailCount);
                            extendDiv(pauseSucCount, $(".tempo-task-succeed"));
                            extendDiv(pauseFailCount, $(".tempo-task-failed"));
                        } else if (scheduling == "WAITE") {
                            $(".tempo-task-succeed").val("成功" + waiteSucCount);
                            $(".tempo-task-failed").val("失败" + waiteFailCount);
                            extendDiv(waiteSucCount, $(".tempo-task-succeed"));
                            extendDiv(waiteFailCount, $(".tempo-task-failed"));
                        } else if (scheduling == "AWAIT") {
                            $(".tempo-task-succeed").val("成功" + awaitSucCount);
                            $(".tempo-task-failed").val("失败" + awaitFailCount);
                            extendDiv(awaitSucCount, $(".tempo-task-succeed"));
                            extendDiv(awaitFailCount, $(".tempo-task-failed"));
                        } else if (scheduling == "COMPLETE") {
                            $(".tempo-task-succeed").val("成功" + completeSucCount);
                            $(".tempo-task-failed").val("失败" + completeFailCount);
                            extendDiv(completeSucCount, $(".tempo-task-succeed"));
                            extendDiv(completeFailCount, $(".tempo-task-failed"));
                        } else {
                            $(".tempo-task-succeed").val("成功" + allSuccCounts);
                            $(".tempo-task-failed").val("失败" + allFailCounts);
                            extendDiv(allSuccCounts, $(".tempo-task-succeed"));
                            extendDiv(allFailCounts, $(".tempo-task-failed"));
                        }
                        updatestaticsInfo(resultdata);
                        bindJobGridEvent.apply(that);
                    }
                });
                if (datas.rows.length > 0) {
                    $(".tempo-message").css("display", "none");
                    $('#jobContainer').find('.ui-paging-info').show()
                } else {
                    $('#jobContainer').find('.ui-paging-info').hide();
                    $(".tempo-message").css("display", "");
                    if (scheduling == 'PAUSED') {
                        $(".tempo-message").children().html("暂无数据");
                    } else if (scheduling == 'WAITE') {
                        $(".tempo-message").children().html("暂无数据");
                    } else if (scheduling == 'AWAIT') {
                        $(".tempo-message").children().html("暂无数据");
                    } else if (scheduling == 'COMPLETE') {
                        $(".tempo-message").children().html("暂无数据");
                    } else {
                        $(".tempo-message").children().html("暂无数据,请在发布区新建调度");
                    }
                }
                $(this).data('rows', rows);
                $("#jobContainer").css("height", "100% !important");
                $("#jqgh_mine-opt-job-grid_cb").css("padding-left", "12px");
                $("#jqgh_mine-opt-job-grid_cb").parent().css("width", "35px");
                $(".viewlog").parent().css("padding-left", "16px");
                $("#jqgh_mine-opt-job-grid_logs").css("padding-left", "15px");
                $(".ui-jqgrid-view ").css("height", "auto");
                $this.find(".ui-jqgrid-hbox").css("width", "100%");
                $(".ui-jqgrid-htable").css("width", "100%");
                $("#mine-opt-job-grid").css("width", "100%");
                var browser = $.support.clearCloneStyle;
                var screenWidth = screen.width;
                if (browser) {
                    $this.find("input.tempo-checkbox+label").css("font-size", "12px");
                } else {
                    if (screenWidth == 1366) {
                        //解决IE11下复选框过大问题
                        $this.find("input.tempo-checkbox+label").css("font-size", "10px");
                    }
                }
                //判断浏览器是否为ie浏览器
                if ((TempoUtils.isIE()) && screenWidth == 1366) {
                    //解决IE11下复选框过大问题
                    $this.find("input.tempo-checkbox+label").css("font-size", "10px");
                }
                //解决显示列过少，遮罩层遮盖全选按钮
                // $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                var headOverDivLeft = $("#jqgh_mine-opt-job-grid_cb").parent().width();
                var afterSelectWidth = $this.find(".after_select").width();
                $this.find(".after_selecthead").css("margin-left", headOverDivLeft);
                var calc = "calc(100% - " + (headOverDivLeft + 120) + "px)";
                $this.find(".after_select").css("width", calc);
                $this.find(".after_select").css("margin-left", headOverDivLeft + 95);
            },
            beforeRequest: function () {

                var current_page = $(this).getGridParam("page");//获取返回的当前页
                var total_page = $(this).getGridParam("lastpage");//获取总页数
                var cont_page = allDatas.length / $(this).getGridParam("rowNum") + 1;
                if (total_page != 0 && current_page > cont_page) {
                    //当输入页码大于总页码时，加载到最后一页
                    that.grid.datagrid("reloadGridToLastPage", {}, true, true, total_page);
                }
                getColumnInfo();
            },

            onSelectAll: function (rowids, status) {
                var multiselect = that.grid.jqGrid().getGridParam("multiselect");
                var seleccount = that.grid.datagrid("getSelectRowIds").length;
                $(".tempo-datagrid-trigger-name").css("color", "black");

                $(".selectedSpan").text("已选择 " + seleccount + " 条");
                if (multiselect && status) {

                    $this.find(".after_select").show();
                } else {
                    $this.find(".after_select").hide();
                }
            }
        });
        //解决1366分辨率下ie11下表格显示一条黑线问题
        $this.find(".ui-jqgrid-hdiv").css("height", "38px");
        if (navigator.userAgent.indexOf("Firefox") >= 0) {
            $this.find(".ui-jqgrid-hdiv").css("border-bottom", "0px solid #eee");
        } else {
            $this.find(".ui-jqgrid-hdiv").css("border-bottom", "1px solid #eee");
        }
    }

    var updatestaticsInfo = function (rows) {
        var waiteCount = 0;
        var awaitCount = 0;
        var pauseCount = 0;
        var completeCount = 0;
        if (rows && rows.length > 0) {
            for (var i = 0; i < rows.length; i++) {
                var jobInfo = rows[i];
                var trigger = jobInfo.trigger;
                if (trigger) {
                    if ("PAUSED" == trigger.status || "PAUSED_BLOCKED" == trigger.status) {
                        pauseCount++;
                    } else if ("COMPLETE" == trigger.status) {
                        completeCount++;
                    } else if ("AWAIT" == trigger.status) {
                        awaitCount++;
                    } else {
                        waiteCount++;
                    }
                }
                failedCount += jobInfo.failedCount;
                successCount += jobInfo.successCount;
            }
        }

        //统计全部
        var allCount = rows.length;
        $this.find(".tempo-task-all").val("全部" + allCount)
        $this.find(".tempo-task-complete").val("失效" + completeCount);
        $this.find(".tempo-task-waite").val("等待" + awaitCount);
        $this.find(".tempo-task-running").val("生效" + waiteCount);
        $this.find(".tempo-task-pause").val("暂停" + pauseCount);
        //22463 挖掘-成果监测-成果列表：IE11浏览器下调度状态可以点击，点击时有交互状态，统计数据不需要有交互状态，不可点击
        $this.find(".state_succ_bt").attr("disabled", true);
        $this.find(".state_fail_bt").attr("disabled", true);
        $this.find(".tempo-task-succeed").attr("disabled", true);
        $this.find(".tempo-task-failed").attr("disabled", true);
    }

    /**
     * 校验表单
     */
    var validateForm = function (dialog, isEdit, oldName) {
        var v = dialog.find('form').formValidate();
        var jobconfig = TempoUtils.getRecord(dialog.find('form'));
        var triggerName = jobconfig.name;
        if (oldName != triggerName && isEdit) {
            var isRaname = false;
            $.ajax({
                url: contextPath + '/api/ai/mine/publish/listAllTriggerName',
                type: 'post',
                async: false,
                success: function (triggerNames) {
                    if (triggerNames) {
                        isRaname = triggerNames.indexOf(triggerName) > -1;
                    }
                }
            });
            if (isRaname) {
                $("<div/>").alert({msg: TempoUtils.locale("mine.tasknameerror"), height: 180});
                return false;
            }
        }
        return v && (function () {
            console.log(jobconfig);
            if (jobconfig.starttime && jobconfig.endtime) {
                var s = new Date(jobconfig.starttime);
                var e = new Date(jobconfig.endtime);
                if (s.getTime() > e.getTime()) {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.shengxiaoshijianerror"), height: 180});
                    return false;
                }
            }
            if (jobconfig.stime && jobconfig.etime) {
                if (jobconfig.stime >= jobconfig.etime && jobconfig.runType == 'inner-day') {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.kaishishijianerror"), height: 180});
                    return false;
                }
                if (jobconfig.stime == jobconfig.etime && jobconfig.runType == 'outer-day') {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.schedule-stime-not-equls-etime"), height: 180});
                    return false;
                }
            }
            return true;
        })();
    }

    var getCheckRowDatas = function () {
        var gridTable = $this.find('#mine-opt-job-grid');
        var checkedRowIds = gridTable.datagrid("getCheckedRowIds");
        if (checkedRowIds.length == 0) {
            $("<div/>").alert({msg: "未选择批量操作的任务！", height: 180});
            return false;
        } else {
            var lastEditId = gridTable.datagrid("getLastEditId");
            if (lastEditId) {
                gridTable.datagrid("saveRow", lastEditId);
            }
            var checkedRowDatas = [];
            var allRowDatas = gridTable.datagrid("getRowData");
            for (var i = 0; i < checkedRowIds.length; i++) {
                for (var j = 0; j < allRowDatas.length; j++) {
                    if (checkedRowIds[i] == allRowDatas[j].id) {
                        var rowData = allRowDatas[j];
                        var successSpan = rowData["trigger.status"].split("：")[1];
                        var failedSpan = rowData["trigger.status"].split("：")[1];
                        //获取成功次数
                        var successCount = Number(successSpan.substring(0, successSpan.indexOf("次")));
                        //获取失败次数
                        var failedCount = Number(failedSpan.substring(0, failedSpan.indexOf("次")));
                        checkedRowDatas.push({
                            id: rowData.id,
                            triggerId: rowData.jobId,
                            taskName: rowData["trigger.name"],
                            logNum: successCount + failedCount
                        });
                    }
                }
            }
            return checkedRowDatas;

        }
    }
    var form = $this.find('.queryJobSchedulingForm').css("display", "block");
    var initOrrefresh = function (isReloadGrid) {
        if (isReloadGrid != false) {
            initJobGrid();
        }
        if ($this.find('.view-container').height() - 98 > 0) {
            $this.find('.publish_tab').height($this.find('.view-container').height() - 98)
        }
        if (selectStatus == "false") {
            $(".trigger-status").parent().css("padding-left", "25px");
        } else if (selectStatus == "true") {
            $(".trigger-status").parent().css("padding-left", "25px");
        }
        TempoUtils.parserUi(form, {});
        //判断筛选框里是否有值，如没值就将蓝点隐藏
        var if_to_hide = function () {
            // 获取筛选div里的搜索input框
            var inputs = $('#shaixuanDiv').find('input');
            // 定义是否有数据标识 true表示有数据
            var hasValue = false;
            for (var i = 0; i < inputs.length; i++) {
                if (inputs.eq(i).val().trim() != "") {
                    hasValue = true;
                    break;
                }
            }
            // 如果搜索框中有值，则显示图标
            if (hasValue) {
                $("#ifshaixuan").removeAttr('style');
                $(".sizer-reset").css("color", "#5185e4")
            } else {
                $("#ifshaixuan").hide();
            }
        }
        form.find('[name="starttime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onClose: function (selectedDate) {

                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="endtime"]').datepicker("option", "minDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="endtime"]').datepicker("option", "minDate", d2str);
            },
            onSelect: function (value) {
                if_to_hide();
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                if_to_hide();
            }
        }).css("width", "100px");
        form.find('[name="endtime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onSelect: function (value) {
                if_to_hide();
            },
            onClose: function (selectedDate) {

                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="starttime"]').datepicker("option", "maxDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="starttime"]').datepicker("option", "maxDate", d2str);
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                //$.datepicker._hideDatepicker(this);
                if_to_hide();
            }
        }).css("width", "100px");

        form.find('[name="laststarttime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onClose: function (selectedDate) {

                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="lastendtime"]').datepicker("option", "minDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="lastendtime"]').datepicker("option", "minDate", d2str);
            },
            onSelect: function (value) {
                if_to_hide();
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                //$.datepicker._hideDatepicker(this);
                if_to_hide();
            }
        }).css("width", "100px");
        form.find('[name="lastendtime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onSelect: function (value) {
                if_to_hide();
            },
            onClose: function (selectedDate) {

                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="laststarttime"]').datepicker("option", "maxDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="laststarttime"]').datepicker("option", "maxDate", d2str);
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                //$.datepicker._hideDatepicker(this);
                if_to_hide();
            }
        }).css("width", "100px");

        form.find('[name="createStartTime"]').datepicker(
            {
                dateFormat: "yy-mm-dd",
                yearRange: "c-100:",
                // 设置日期的最大时间和最小时间
                minDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() - 100, 0, 1)),
                maxDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() + 1, 0, 1)),
                changeYear: true,
                changeMonth: true,
                width: 50,
                onClose: function (selectedDate) {

                    var d = $(this).datepicker('getDate');
                    if (d == null) {
                        form.find('[name="createEndTime"]').datepicker(
                            "option", "minDate", null);
                        return;
                    }
                    var d2 = new Date(d.getTime());
                    var d2str = d2.Format('yyyy-MM-dd');
                    form.find('[name="createEndTime"]').datepicker(
                        "option", "minDate", d2str);
                },
                onSelect: function (value) {
                    if_to_hide();
                },
                onChangeMonthYear: function (year, month, inst) {
                    var month = inst.selectedMonth + 1;
                    var day = inst.selectedDay;
                    var format = function (v) {
                        return String(v).length > 1 ? v : ('0' + v)
                    }
                    $(this).val(
                        inst.selectedYear + '-' + format(month) + '-'
                        + format(inst.selectedDay));
                    //$.datepicker._hideDatepicker(this);
                    if_to_hide();
                }
            }).css("width", "100px");
        form.find('[name="createEndTime"]').datepicker(
            {
                dateFormat: "yy-mm-dd",
                yearRange: "c-100:",
                // 设置日期的最大时间和最小时间
                minDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() - 100, 0, 1)),
                maxDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() + 1, 0, 1)),
                changeYear: true,
                changeMonth: true,
                onSelect: function (value) {
                    if_to_hide();
                },
                onClose: function (selectedDate) {

                    var d = $(this).datepicker('getDate');
                    if (d == null) {
                        form.find('[name="createStartTime"]').datepicker(
                            "option", "maxDate", null);
                        return;
                    }
                    var d2 = new Date(d.getTime());
                    var d2str = d2.Format('yyyy-MM-dd');
                    form.find('[name="createStartTime"]').datepicker(
                        "option", "maxDate", d2str);
                },
                onChangeMonthYear: function (year, month, inst) {
                    var month = inst.selectedMonth + 1;
                    var day = inst.selectedDay;
                    var format = function (v) {
                        return String(v).length > 1 ? v : ('0' + v)
                    }
                    $(this).val(
                        inst.selectedYear + '-' + format(month) + '-'
                        + format(inst.selectedDay));
                    //$.datepicker._hideDatepicker(this);
                    if_to_hide();
                }
            }).css("width", "100px");
        $(".queryBtn").button({
            emphasize: true,

            click: function () {
                $("#shaixuanDiv").hide();
                isSearch = true;
                $(".tempo-tableset").show();
                var starttime = form.find('[name="starttime"]').datepicker('getDate');
                var endtime = form.find('[name="endtime"]').datepicker('getDate');
                var laststarttime = form.find('[name="laststarttime"]').datepicker('getDate');
                var lastendtime = form.find('[name="lastendtime"]').datepicker('getDate');
                var jobstatus = form.find('[name="jobstatus"]').val();
                var jobname = form.find('[name="jobname"]').val();
                var jobcreator = form.find('[name="jobcreator"]').val();
                var workspaceName = form.find('[name="workspaceName"]').val();
                var applicationName = form.find('[name="applicationName"]').val();
                var lastExcuteStatus = form.find('[name="lastExcuteStatus"]').val();
                var createStartTime = form.find('[name="createStartTime"]').datepicker('getDate');
                var createEndTime = form.find('[name="createEndTime"]').datepicker('getDate');


                var data = {
                    starttime: starttime ? DateUtils.formatDate(starttime, 'yyyy-MM-dd') : null,
                    endtime: endtime ? DateUtils.formatDate(endtime, 'yyyy-MM-dd') : null,
                    laststarttime: laststarttime ? DateUtils.formatDate(laststarttime, 'yyyy-MM-dd') : null,
                    lastendtime: lastendtime ? DateUtils.formatDate(lastendtime, 'yyyy-MM-dd') : null,
                    name: jobname,
                    creator: jobcreator,
                    jobstatus: jobstatus,
                    workspaceName: workspaceName,
                    applicationName: applicationName,
                    lastExcuteStatus: lastExcuteStatus,
                    createStartTime: createStartTime ? DateUtils.formatDate(createStartTime, 'yyyy-MM-dd') : null,
                    createEndTime: createEndTime ? DateUtils.formatDate(createEndTime, 'yyyy-MM-dd') : null,
                    querydata: "true"
                };
                searchData = data;
                $this.find(".ui-icon-seek-first").trigger("click");
                setTimeout(function () {
                    that.grid.jqGrid('setGridParam',
                        {
                            postData: data
                        }).trigger("reloadGrid");
                    delete data["querydata"];
                    $this.find(".tempo-ui-icon-refresh").trigger("click");
                }, 500);
                return false;
            }
        }).css("width", "60px");
        form.find('.resetBtn').button({
            emphasize: true,
            click: function () {
                form[0].reset();
                form.find('[name="endtime"]').datepicker("option", "minDate", DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)));
                form.find('[name="starttime"]').datepicker("option", "maxDate", DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)));
                form.find('[name="lastendtime"]').datepicker("option", "minDate", DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)));
                form.find('[name="laststarttime"]').datepicker("option", "maxDate", DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)));
                form.find('[name="createEndTime"]').datepicker("option", "minDate", DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)));
                form.find('[name="createStartTime"]').datepicker("option", "maxDate", DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)));
                form.find('[name="jobstatus"]').val('').selectmenu('refresh');
                form.find('[name="jobname"]').val('');
                form.find('[name="jobcreator"]').val('');
                form.find('[name="workspaceName"]').val('');
                form.find('[name="applicationName"]').val('');
                return false;
            }
        }).css("width", "60px");

        form.find('.task-opts-btn').button({
            emphasize: true,
            click: function (e) {
            }
        });

        form.find('.task-opts-btn').on("mouseover", function (event) {
            var offset = $(this).offset();
            form.find("#tempo-header-task-opts-infos").css({
                left: offset.left,
                top: offset.top + 26
            });
            form.find("#tempo-header-task-opts-infos").show();
        });

        form.find('.task-opts-btn').on("mouseout", function () {
            form.find("#tempo-header-task-opts-infos").hide();

        });

        form.find("#tempo-header-task-opts-infos").on("mouseover", function () {
            form.find("#tempo-header-task-opts-infos").show();

        })
        form.find("#tempo-header-task-opts-infos").on("mouseout", function () {
            form.find("#tempo-header-task-opts-infos").hide();
        })
        //$(".ui-jqgrid-view ").css("height","745px");
        //批量手动执行
        $("#tempo-header-task-opts-start-flow").on("click", function (e) {
            var seleccount = that.grid.datagrid("getSelectRowIds").length;
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: "已选中" + seleccount + "个任务，是否确定批量手动执行？",
                ok: function () {
                    var allselectDatas = that.grid.datagrid("getSelectRowData");
                    var requestData = [];
                    var errorData = [];
                    for (var i = 0; i < allselectDatas.length; i++) {
                        if (rowDatas[allselectDatas[i]["id"]].isRunning == "true") {
                            errorData.push(rowDatas[allselectDatas[i]["id"]].trigger.name);
                        } else {
                            requestData.push({
                                id: allselectDatas[i].id,
                                jobId: allselectDatas[i].jobId,
                                logNum: allselectDatas[i].logNum,
                                "trigger.name": allselectDatas[i]["trigger.name"],
                            })
                        }
                    }
                    if (errorData.length > 0) {
                        var msg = errorData[0];
                        for (var i = 1; i < errorData.length; i++) {
                            msg += "," + errorData[i];
                        }
                        $("<div/>").alert({msg: msg + "任务正在执行，请稍后发起手动执行", height: 180});
                    }
                    var process = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: contextPath + '/api/ai/app/schedule/job/batchmanual',
                        type: 'post',
                        data: {
                            batchdata: JSON.stringify(requestData)
                        },
                        dataType: 'json',
                        success: function (obj) {
                            process.tempoprogressbar("destroy");
                            var data = obj.data;

                            if (data && data.length > 0) {
                                if (obj.success) {
                                    $("<div/>").alert({msg: "任务" + data.join(",") + "正在执行中，请稍后再试", height: 180});
                                }
                            }
                            $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                            $(".after_select").hide()
                        }, error: function (obj) {
                            process.tempoprogressbar("destroy");
                        }
                    });

                }
            });
        });
        //批量停止
        $(".tempo-header-task-opts-stop-flow").on("click", function (e) {

            var seleccount = that.grid.datagrid("getSelectRowIds").length;
            $("<div>").confirm({
                width: 500,
                height: 197,

                msg: "已选中" + seleccount + "个任务，是否确定批量停止执行？",
                ok: function (job) {

                    var allselectDatas = that.grid.datagrid("getSelectRowData");
                    var requestData = [];
                    for (var i = 0; i < allselectDatas.length; i++) {
                        requestData.push({
                            id: allselectDatas[i].id,
                            jobId: allselectDatas[i].jobId,
                            logNum: allselectDatas[i].logNum
                        })
                    }
                    var process = $("<div/>").tempoprogressbar();
                    var logNum = successCount + failedCount;
                    $.ajax({
                        url: contextPath + '/api/ai/app/schedule/job/batchstop',
                        type: 'post',
                        data: {
                            batchdata: JSON.stringify(requestData),
                        },
                        dataType: 'json',
                        success: function (obj) {
                            // $(".after_selecthead").hide();
                            // $(".after_selecthead").css("display","none");

                            if (obj.success) {
                                $("<div/>").alert({msg: TempoUtils.locale("mine.publish-job-killed"), height: 180});
                            } else {
                                $("<div/>").alert({msg: TempoUtils.locale("mine.publish-job-notexists"), height: 180});
                            }
                            process.tempoprogressbar("destroy");
                            $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                            $(".after_select").hide()
                        }, error: function (obj) {
                            process.tempoprogressbar("destroy");
                        }
                    });

                }
            });
        });
        //批量暂停
        $("#tempo-header-task-opts-pause-task").on("click", function (e) {
            var seleccount = that.grid.datagrid("getSelectRowIds").length;
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: "已选中" + seleccount + "个任务，是否确定批量暂停执行？",
                ok: function () {
                    var allselectDatas = that.grid.datagrid("getSelectRowData");
                    var requestData = [];
                    for (var i = 0; i < allselectDatas.length; i++) {
                        requestData.push({
                            id: allselectDatas[i].id,
                            jobId: allselectDatas[i].jobId,
                            logNum: allselectDatas[i].logNum
                        })
                    }
                    var process = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: contextPath + '/api/ai/app/schedule/job/batchpause',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            batchdata: JSON.stringify(requestData)
                        },
                        success: function (obj) {
                            process.tempoprogressbar("destroy");

                            var data = obj.data;
                            if (data && data.length > 0) {
                                if (obj.success) {
                                    $("<div/>").alert({msg: "任务" + data.join(",") + "已经失效不允许暂停", height: 180});
                                }
                            }
                            $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                            $(".after_select").hide()
                        }, error: function (obj) {
                            process.tempoprogressbar("destroy");
                        }
                    });

                }
            });
        });
        //批量删除任务
        $(".tempo-header-task-opts-delete-task").on("click", function (e) {

            var seleccount = that.grid.datagrid("getSelectRowIds").length;
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: "已选中" + seleccount + "个任务，是否确定批量删除执行？",
                ok: function () {
                    var allselectDatas = that.grid.datagrid("getSelectRowData");
                    var requestData = [];
                    for (var i = 0; i < allselectDatas.length; i++) {
                        requestData.push({
                            id: allselectDatas[i].id,
                            jobId: allselectDatas[i].jobId,
                            logNum: allselectDatas[i].logNum
                        })
                    }
                    var process = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: contextPath + '/api/ai/app/schedule/job/batchdelete',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            batchdata: JSON.stringify(requestData)
                        },
                        success: function (obj) {

                            process.tempoprogressbar("destroy");
                            $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                            $(".after_select").hide()
                        }, error: function (obj) {
                            process.tempoprogressbar("destroy");
                        }
                    });

                }
            });
        });
    }
    var openViewDetailDialog = function (job) {
        var paramDialog = $('<div class="" style="width:100%;height:500px;"/></div>').attr("id", 'app-flow-scheduling-execute-detail');
        var parentDiv = $this.find("#asdfghjk");
        $("#ui-datepicker-div").remove();
        paramDialog.appendTo(parentDiv);
        paramDialog.dialog({
            title: TempoUtils.locale("aiview.taskdetail"),
            width: $this.width(),
            height: $this.height(),
            resizable: false,
            modal: true,
            close: function () {
                $(".task-right-bot-container")[0].innerHTML = "";
                paramDialog.remove();
                paramDialog.dialog('destroy');
            },
            open: function () {

                var _this = this;
                $(_this).empty();
                var datas;
                $m.loadPage(contextPath + "/api/ai/app/statistics/view/flowScheMange", $(_this), job.SERVICEID, {"job": job});
                $(".ui-dialog-title").before("<span class='ui-icon tempo-ui-icon tempo-ui-icon-leftarrows-undertint tempo-leftback' style='float: left;margin-top: 12px;'></span>")
                $("#app-flow-scheduling-execute-detail").prev().find("button").css("display", "none")
                $(".ui-draggable-handle").css("cursor", "auto");
                $(".tempo-leftback").css("cursor", "pointer");
                $(".ui-dialog-title").css("font-size", "14px");
                $(".ui-dialog-title").css("font-weight", "bold");
                $(".ui-dialog-title").css("color", "#445265");
                $(".tempo-leftback").click(function () {
                    $this.find("#ui-datepicker-div").remove();
                    $(".task-right-mid ul li").css("border-bottom", "none");
                    $(".ui-dialog-title").css("font-size", "14px");
                    $(".ui-dialog-title").css("font-weight", "bold");
                    paramDialog.dialog('destroy');
                    that.grid.jqGrid().trigger("reloadGrid");
                    $(".after_select").hide();


                    //$this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                });
            }
        });
    }

    var modifyInfo = function (job) {
        $('.rs-right-top span[id="task-creator"]').text(job.creatorName);
        $('.rs-right-top span[id="belong_workspace"]').text(job.workspaceName);
        $('.rs-right-top span[id="belong_theme"]').text(job.applicationName);
        $('#ca-name').text(job.publishFlowNames);


        $('.rs-right-top span[id="belong_workspace"]').attr("title", job.workspaceName);
        $('.rs-right-top span[id="belong_theme"]').attr("title", job.applicationName);
        $('#ca-name').attr("title", job.publishFlowNames);
        //IE浏览器下格式化日期的方法
        var iEformartDate = function (value, fmt) {
            if (value !== null) {
                var d = '';
                if (value instanceof Date) {
                    d = value;
                } else {
                    var arr = value.split(" ");
                    var dd = arr[0].split("-");
                    var t = arr[1].split(":");
                    d = new Date();
                    d.setFullYear(dd[0], dd[1] - 1, dd[2]);
                    d.setHours(t[0], t[1], t[2], 0);
                }
                var o = {
                    'M+': d.getMonth() + 1,//月
                    'd+': d.getDate(),//日
                    'H+': d.getHours(),//时
                    'm+': d.getUTCMinutes(),//分
                    's+': d.getSeconds(),//秒
                    'q+': Math.floor((d.getMonth() + 3) / 3),//季度
                    'S+': d.getMilliseconds()
                }
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(
                        RegExp.$1,
                        (d.getFullYear() + "").substr(4 - RegExp.$1.length)
                    )
                }
                for (var k in o) {
                    if (new RegExp('(' + k + ')').test(fmt)) {
                        fmt = fmt.replace(RegExp.$1,
                            RegExp.$1.length === 1 ? o[k] : ('' + o[k]).substr(('' + o[k].length))
                        );
                    }
                }
                return fmt
            }
        }
        $('#task-createTime').text(job.createTime);
        $.ajax({
            url: contextPath + '/api/ai/mine/publish/listJobInfo',
            type: 'post',
            dataType: 'json',
            data: {
                id: job.id
            },
            success: function (result) {

                if ("true" == result.flag) {
                    var job = result.job;
                    var taskStatusDesc = "生效";
                    if (job.trigger.status == "PAUSED" || job.trigger.status == "PAUSED_BLOCKED") {
                        taskStatusDesc = '暂停';
                    } else if (job.trigger.status == "COMPLETE") {
                        taskStatusDesc = '失效';
                    } else if (job.trigger.status == "AWAIT") {
                        taskStatusDesc = '等待';
                    }

                    //$('.rs-right-top span[id="task-createTime"]').text(formatCreateTime(job.createTime));
                    $('.rs-right-mid span[class="task-runtStatus"]').text(taskStatusDesc).attr("id", job.id);
                    $('.tempo-app-task-view span[id="ca-name"]').text(job.trigger.name);
                }
            }
        });

    }
    var loadTaskRightPage = function (job) {
        $('.task-right-bot li.unsort').show();
        $m.loadPage(contextPath + "/api/ai/app/view/overview?id=" + job.publishFlowIds + "&&t=" + TempoUtils.uuid() + "&&serviceId=" + job.publishFlowIds, $(".task-right-bot-container"));
        $("#overview").css("border-bottom-color", "#2E90E3");
        $("#overview").css("border-bottom-width", "initial");
        $("#overview").css("border-bottom-style", "inset");
        $("#overview").off('click').on('click', function () {
            $(".task-right-bot-container").empty();
            $("#overview").css("border-bottom-color", "#2E90E3");
            $("#overview").css("border-bottom-width", "initial");
            $("#overview").css("border-bottom-style", "inset");
            $("#taskconfiguration").css("border-bottom", "none");
            $("#taskmonitor").css("border-bottom", "none");
            loadTaskRightPage(job);
            //$m.loadPage(contextPath + "/api/ai/app/view/overview?id="+job.id+"&&t="+TempoUtils.uuid()+"&&serviceId="+job.publishFlowIds, $(".task-right-bot-container"));

        });
        $("#taskconfiguration").off('click').on('click', function () {
            $(".task-right-bot-container").empty();
            $("#overview").css("border-bottom", "none");
            $("#taskmonitor").css("border-bottom", "none");
            $("#taskconfiguration").css("border-bottom-color", "#2E90E3");
            $("#taskconfiguration").css("border-bottom-width", "initial");
            $("#taskconfiguration").css("border-bottom-style", "inset");
            $m.loadPage(contextPath + "/api/ai/app/view/taskconfiguration?id=" + job.id + "&&t=" + TempoUtils.uuid() + "&&serviceId=" + job.publishFlowIds, $(".task-right-bot-container"));

        });
        $("#taskmonitor").off('click').on('click', function () {
            $(".task-right-bot-container").empty();
            $("#overview").css("border-bottom", "none");
            $("#taskconfiguration").css("border-bottom", "none");
            $("#taskmonitor").css("border-bottom-color", "#2E90E3");
            $("#taskmonitor").css("border-bottom-width", "initial");
            $("#taskmonitor").css("border-bottom-style", "inset");
            $m.loadPage(contextPath + "/api/ai/app/view/taskmonitor?id=" + job.id + "&&t=" + TempoUtils.uuid() + "&&serviceId=" + job.publishFlowIds, $(".task-right-bot-container"));

        })
    }

    var load = function (data, flowId, job, idx, jobId) {
        window.apiInsight = 'inline';
        var alg = data.alg;
        window[window.constant.MNODES] = {};
        // 将获取的所有算法节点保存到页面window对象中
        window[window.constant.DATAMINE_COMMONOPER] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_COMMONOPER]);
        window[window.constant.DATAMINE_TYP] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_TYP]);
        window[window.constant.DATAMINE_PRE] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_PRE]);
        window[window.constant.DATAMINE_DATA] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_DATA]);
        window[window.constant.DATAMINE_CONTROL] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_CONTROL]);
        window[window.constant.DATAMINE_CHART] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_CHART]);
        window[window.constant.DATAMINE_ALG] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_ALG]);
        window[window.constant.DATAMINE_EXTEND] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_EXTEND]);
        window[window.constant.DATAMINE_MODEL] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_MODEL]);
        window[window.constant.USER_DEFINED] = TempoPluginUtils
            .pluginExtend(alg[window.constant.USER_DEFINED]);
        window[window.constant.DATAMINE_FUNSION] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_FUNSION]);
        window[window.constant.DATAMINE_FEATUREENG] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_FEATUREENG]);
        window[window.constant.DATAMINE_STATISTICS] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_STATISTICS]);
        window[window.constant.DATAMINE_DEEPLEARNING] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_DEEPLEARNING]);
        window[window.constant.DATAMINE_INTEGRATED] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_INTEGRATED]);
        window[window.constant.DATAMINE_AUTO] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_AUTO]);
        window[window.constant.DATAMINE_CF] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_CF]);
        window[window.constant.DATAMINE_TEXTMINING] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_TEXTMINING]);

        window[window.constant.DATAMINE_DEFAULT] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_DEFAULT]);

        //新增分类处理
        for (var i in window[window.constant.DATAMINE_DEFAULT]) {
            var key = window[window.constant.DATAMINE_DEFAULT][i]
            var eleObject = new Object();
            eleObject[i] = window[window.constant.DATAMINE_DEFAULT][i];
            window[key.type] = eleObject
        }
        // 将国际化字典保存
        var i18ns = data[window.constant.I18NDICT];
        for (var i in i18ns) {
            TempoUtils.locale(i, i18ns[i]);
        }
        var groupCategory = function (eles) {
            for (var p in eles) {
                var ele = eles[p];
                window[window.constant.MNODES][ele.id] = ele;
                ele.title = ele.name;
                var icon = 'ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-library-unselect';
                ele.icon = icon;
                if (ele.libraryIcon) {
                    ele.icon += " tempo-mine-library-node-" + ele.id;
                }

            }
        }
        groupCategory(window[window.constant.DATAMINE_COMMONOPER]);
        groupCategory(window[window.constant.DATAMINE_TYP]);
        groupCategory(window[window.constant.DATAMINE_PRE]);
        groupCategory(window[window.constant.DATAMINE_DATA]);
        groupCategory(window[window.constant.DATAMINE_CONTROL]);
        groupCategory(window[window.constant.DATAMINE_CHART]);
        groupCategory(window[window.constant.DATAMINE_ALG]);
        groupCategory(window[window.constant.DATAMINE_EXTEND]);
        groupCategory(window[window.constant.DATAMINE_MODEL]);
        groupCategory(window[window.constant.USER_DEFINED]);
        groupCategory(window[window.constant.DATAMINE_FUNSION]);
        groupCategory(window[window.constant.DATAMINE_FEATUREENG]);
        groupCategory(window[window.constant.DATAMINE_STATISTICS]);
        groupCategory(window[window.constant.DATAMINE_DEEPLEARNING]);
        groupCategory(window[window.constant.DATAMINE_INTEGRATED]);
        groupCategory(window[window.constant.DATAMINE_AUTO]);
        groupCategory(window[window.constant.DATAMINE_CF]);
        groupCategory(window[window.constant.DATAMINE_TEXTMINING]);
        groupCategory(window[window.constant.PROTOCOL_RESOLUTION]);
        groupCategory(window[window.constant.TARGET_RECOGNITION]);
        groupCategory(window[window.constant.TOPOLOGICAL_ANALYSIS]);
        groupCategory(window[window.constant.VULNERABILITY_ANALYSIS]);
        groupCategory(window[window.constant.AGGRESIVE_BEHAVIOR_ANALYSIS]);
        groupCategory(window[window.constant.ENCRYPTED_DATA_ANALYSIS]);

        ScheduleMineViewlingController(flowId, false, job, idx, jobId);
    }

    initOrrefresh();

    //初始化成果管理页面页面变动监听事件
    var timeout = 0;
    window.addEventListener('resize', function () {
        if (timeout != 0) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(function () {
            that.grid.datagrid("reloadGrid");
            //调整弹框宽度
            if ($this.find("#app-flow-scheduling-execute-detail").length > 0) {
                $this.find("#app-flow-scheduling-execute-detail").parent().css("width", $this.width());
                if ($this.find("#app-flow-scheduling-execute-detail").find(".tempo-head-li").length > 0) {
                    var tempoHeadLis = $this.find("#app-flow-scheduling-execute-detail").find(".tempo-head-li");
                    for (var i = 0; i < tempoHeadLis.length; i++) {
                        var $tempoHeadLi = $(tempoHeadLis[i]);
                        if ($tempoHeadLi.css("border-bottom") == '2px solid rgb(31, 115, 182)') {
                            //触发选中页签的点击事件，重新触发页面样式
                            $tempoHeadLi.trigger("click");
                            break;
                        }
                    }
                }
            }
            timeout = 0;
        }, 200)
    });
});